import { mqtt } from '@/utils/electron'

const state = {
  isConnected: false,
  connectionConfig: {
    url: '',
    username: '',
    password: '',
    clientId: '',
    keepAlive: 60,
    cleanSession: true
  },
  subscriptions: [],
  messages: [],
  maxMessages: 1000
}

const mutations = {
  SET_CONNECTED(state, connected) {
    state.isConnected = connected
  },
  
  UPDATE_CONNECTION_CONFIG(state, config) {
    state.connectionConfig = { ...state.connectionConfig, ...config }
  },
  
  ADD_SUBSCRIPTION(state, subscription) {
    const exists = state.subscriptions.find(s => s.topic === subscription.topic)
    if (!exists) {
      state.subscriptions.push({
        ...subscription,
        id: `sub_${Date.now()}`,
        subscribedAt: new Date().toISOString()
      })
    }
  },
  
  REMOVE_SUBSCRIPTION(state, topic) {
    state.subscriptions = state.subscriptions.filter(s => s.topic !== topic)
  },
  
  ADD_MESSAGE(state, message) {
    state.messages.unshift({
      ...message,
      id: `msg_${Date.now()}`
    })
    if (state.messages.length > state.maxMessages) {
      state.messages = state.messages.slice(0, state.maxMessages)
    }
  },
  
  CLEAR_MESSAGES(state) {
    state.messages = []
  }
}

const actions = {
  async connect({ state, commit }) {
    if (state.isConnected) return
    
    const result = await mqtt.connect(state.connectionConfig)
    
    if (result.success) {
      mqtt.onConnected(() => {
        commit('SET_CONNECTED', true)
      })
      
      mqtt.onMessage((message) => {
        commit('ADD_MESSAGE', message)
      })
      
      mqtt.onError((error) => {
        console.error('MQTT Error:', error)
      })
      
      mqtt.onDisconnected(() => {
        commit('SET_CONNECTED', false)
      })
    }
    
    return result
  },
  
  async disconnect({ commit }) {
    const result = await mqtt.disconnect()
    if (result.success) {
      commit('SET_CONNECTED', false)
    }
    return result
  },
  
  async subscribe({ commit }, { topic, qos = 0 }) {
    const result = await mqtt.subscribe(topic, qos)
    if (result.success) {
      commit('ADD_SUBSCRIPTION', { topic, qos })
    }
    return result
  },
  
  async unsubscribe({ commit }, topic) {
    commit('REMOVE_SUBSCRIPTION', topic)
  },
  
  async publish(context, { topic, message, qos = 0, retain = false }) {
    return await mqtt.publish(topic, message, qos, retain)
  },
  
  updateConnectionConfig({ commit }, config) {
    commit('UPDATE_CONNECTION_CONFIG', config)
  },
  
  clearMessages({ commit }) {
    commit('CLEAR_MESSAGES')
  },
  
  applyConfig({ commit }, config) {
    if (config.connectionConfig) {
      commit('UPDATE_CONNECTION_CONFIG', config.connectionConfig)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}